package com.minelx.datamicroscope.core.condition;

import java.util.LinkedList;
import java.util.List;
import java.util.function.Supplier;

public class ResourceNanny<T extends AutoCloseable> implements AutoCloseable {

	private final List<T> createdResources;

	private final Supplier<T> resourceSupplier;

	public ResourceNanny(Supplier<T> resourceSupplier) {
		this.resourceSupplier = resourceSupplier;
		createdResources = new LinkedList<>();
	}

	public T create() {
		T result = resourceSupplier.get();
		createdResources.add(result);
		return result;
	}

	@Override
	public void close() {
		createdResources.forEach(closeable -> {
			try {
				closeable.close();
			} catch (Exception e) {
				throw new RuntimeException("error while closing resources.", e);
			}
		});
	}
}
